package com.bjy.qa.service.manage.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bjy.qa.dao.manage.CompanyDao;
import com.bjy.qa.dao.manage.ProjectDao;
import com.bjy.qa.entity.MyPage;
import com.bjy.qa.entity.ResponsePagingData;
import com.bjy.qa.entity.manage.Company;
import com.bjy.qa.entity.manage.Project;
import com.bjy.qa.exception.MyException;
import com.bjy.qa.service.manage.ICompanyService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CompanyService implements ICompanyService {
    @Resource
    CompanyDao companyDao;

    @Resource
    ProjectDao projectDao;

    @Override
    public List<Company> selectAll() {
        return companyDao.selectList(new QueryWrapper<>());
    }

    @Override
    public ResponsePagingData list(MyPage<Company> myPage) {
        Page<Company> page = new Page(myPage.getPageNum(), myPage.getPageSize()); // 构造待查询 page 对象
        page.setOrders(myPage.getOrders()); // 设置排序字段

        // 构造待查询 QueryWrapper
        Company company = myPage.getQuery();
        QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
        if (company != null) {
            if (StringUtils.isNotBlank(company.getName())) {
                queryWrapper.like("name", company.getName());
            }
        }

        page = companyDao.selectPage(page, queryWrapper); // 按分页查询

        myPage.setTotalRecords(page.getTotal()); // 设置返回总记录数

        return new ResponsePagingData(myPage, page.getRecords());
    }

    @Override
    public Company selectById(Long id) {
        Company company = companyDao.selectById(id);

        List<Project> projectList = projectDao.selectList(new QueryWrapper<Project>().eq("company_id", id));
        company.setProjectList(projectList);

        return company;
    }

    @Override
    public int add(Company company) {
        return companyDao.insert(company);
    }

    @Override
    public int update(Company company) {
        // 更新数据需要清除 UpdatedTime 和 CreatedTime，否则不会自动更新修改时间
        company.setUpdatedAt(null);
        company.setCreatedAt(null);

        return companyDao.updateById(company);
    }

    @Override
    public int delete(Long id) {
        // 删除 company 前，先判断此 company 下的 project 是否都已删除
        QueryWrapper<Project> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id", id);
        if (projectDao.selectCount(queryWrapper) > 0) {
            throw new MyException("删除错误，请先删除此公司下的所有项目！");
        }

        return companyDao.deleteById(id);
    }
}
